﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace Tests {
	// uruchom najpierw MasterSerwer a potem ZTest aby zobaczyć testowe połączenie
	public class Program {
		static StreamReader streamReader;
		static StreamWriter streamWriter;
		static NetworkStream networkStream;
		static TcpClient client;
		static void Handshake() {
			string s = "czesc";
			streamWriter.WriteLine(s);
			streamWriter.Flush();
			Console.WriteLine(">>>" + s);
			s = streamReader.ReadLine();
			Console.WriteLine("<<<" + s);
			if (s.StartsWith("czesc")) {
				s = s.Split(' ')[1];
				networkStream.Close();
				streamReader.Close();
				streamWriter.Close();
				client.Close();
				client = new TcpClient("localhost", int.Parse(s));
				networkStream = client.GetStream();
				streamReader = new StreamReader(networkStream);
				streamWriter = new StreamWriter(networkStream);
				s = "OK";
				Console.WriteLine("Send: " + s);
				streamWriter.WriteLine(s);
				streamWriter.Flush();
				Console.WriteLine("<<<"+streamReader.ReadLine());
			}
		}
		static void Main(string[] args) {
			client = new TcpClient("localhost", 8180);
			networkStream = client.GetStream();
			streamReader = new StreamReader(networkStream);
			streamWriter = new StreamWriter(networkStream);
			Handshake();
			new Thread(new Reader(streamReader).Run).Start();
			string s="";
			while (s != "qiut") {
				s = Console.ReadLine();
				streamWriter.WriteLine(s);
				streamWriter.Flush();
			}
		}
		class Reader {
			StreamReader str;
			internal Reader(StreamReader s) {
				str = s;
			}
			internal void Run() {
				while (true) {
					Console.WriteLine("<<< " + str.ReadLine());
				}
			}
		}
	}
}
